<!-- 销售统计 -->
<template>
    <div class="page has-navbar saleStatic">
        <scroll class="page-content">
            <!-- <datepickerC :value="startDate" label="请选择时间" date-format="yyyy-mm-dd" @input="setStartDate"></datepickerC> -->
            <!-- <datepickerC :value="endDate" label="结束日期" date-format="yyyy-mm-dd" @input="setEndDate"></datepickerC> -->
            <!-- <div class="chartLine" id="chartLine"></div>
            <div class="msgBox">
                <div class="basicMsg clearfix">
                    <div class="msgItem left total">
                        <div class="title">销售总收入</div>
                        <div class="val" v-text="'￥'+(homeData.cash+homeData.alipay+homeData.wechat+homeData.alipayCash+homeData.wechatCash).toFixed(0)"></div>
                    </div>
                    <div class="msgItem left color1">
                        <div class="title">现金</div>
                        <div class="val" v-text="'￥'+homeData.cash.toFixed(0)"></div>
                    </div>
                    <div class="msgItem left color2">
                        <div class="title">支付宝</div>
                        <div class="val" v-text="'￥'+homeData.alipay.toFixed(0)"></div>
                    </div>
                    <div class="msgItem left color3">
                        <div class="title">微信</div>
                        <div class="val" v-text="'￥'+homeData.wechat.toFixed(0)"></div>
                    </div>
                </div>
                <div class="basicMsg clearfix">
                    <div class="msgItem left color4">
                        <div class="title">线下支付宝</div>
                        <div class="val" v-text="'￥'+homeData.alipayCash.toFixed(0)"></div>
                    </div>
                    <div class="msgItem left color5">
                        <div class="title">线下微信</div>
                        <div class="val" v-text="'￥'+homeData.wechatCash.toFixed(0)"></div>
                    </div>
                </div>
                <div class="basicMsg clearfix">
                    <div class="msgItem left spec1">
                        <div class="title">商品剩余总量</div>
                        <div class="val" v-text="homeData.stockSummary.quantity.toFixed(0)"></div>
                    </div>
                    <div class="msgItem left spec1">
                        <div class="title">商品剩余总价值</div>
                        <div class="val" v-text="'￥'+homeData.stockSummary.amount.toFixed(0)"></div>
                    </div>
                </div>
            </div> -->
            <div class="manage-bill">
                <div class="select-date">
                    <span class="prev iconfont icon-jiantou left" @click="changeDate('reduce')"></span>
                    <div class="date">
                        <div class="now-date">{{nowDate}}</div>
                        <div class="end-time">截止23:59:59</div>
                    </div>
                    <span class="next iconfont icon-jiantou right" @click="changeDate('add')"></span>
                </div>
                <!-- <div class="actual-income">
            <span class="actual-income-tit">实际收入：</span>
            <span class="money">1915.00</span>
        </div> -->
                <div class="total-income">
                    <div class="tit">
                        <i class="default-icon"></i>
                        <span class="total-tit">总收入：</span>
                        <span class="money">{{totalAmount | toFixedNum}}</span>
                    </div>
                    <div id="pie" v-show="showPie"></div>
                    <div class="no-income" v-show="!showPie">暂无数据</div>
                    <!-- <div class="pie-help-info">
                        <div class="income-item">
                            <i class="default-icon wechat"></i>
                            <span class="income-name">微信收入:</span>
                            <span class="income-count wechat">{{wechat}}元</span>
                        </div>
                        <div class="income-item">
                            <i class="default-icon ali"></i>
                            <span class="income-name">支付宝收入:</span>
                            <span class="income-count ali">{{ali}}元</span>
                        </div>
                        <div class="income-item">
                            <i class="default-icon cash"></i>
                            <span class="income-name">现金收入:</span>
                            <span class="income-count cash">{{cash}}元</span>
                        </div>
                    </div> -->
                </div>
                <!-- <div class="total-expend">
            <div class="tit">
                <i class="default-icon"></i>
                <span class="total-tit">总支出：</span>
                <span class="money">1900.00</span>
            </div>
            <div id="pie-for-expend"></div>
            <div class="pie-help-info">
                <div class="income-item">
                    <i class="default-icon"></i>
                    <span class="income-name">其他支出:</span>
                    <span class="income-count other">1000元</span>
                </div>
            </div>
        </div> -->
            </div>
            <accordion class="saleStaticAccordion" default-index="0">
                <accordion-item title="分类销售统计" :contentHeight="(homeData.salesItems.length*40+10+nowChild.length*40+10)+''">
                    <div v-for="item in homeData.salesItems" class="goodsBox clearfix" @click="getChild(item)">
                        <div class="goodName left" v-text="item.typeName" :title="item.typeName"></div>
                        <div class="goodPrice right" v-text="'￥'+item.amount.toFixed(2)"></div>
                        <div class="number right" v-text="'×'+item.qty"></div>
                        <div class="child-cont clearfix" v-if="showNowChild&&nowItem.typeName == item.typeName">
                          <div class="child-item" v-for="(itemForChild,indexForChild) in nowChild" :key="indexForChild">
                            <span class="count left">{{itemForChild.qty}} * </span>
                            <span class="name left">{{itemForChild.name}}</span>
                            <span class="amount right">￥{{itemForChild.amount}}</span>
                          </div>
                        </div>
                    </div>
                    <!-- <div class="totalBox">
                        <span class="totalName">总金额</span>
                        <span class="totalNumber" v-text="'￥'+homeData.salesSummary.amount"></span>
                    </div> -->
                </accordion-item>
                <accordion-item title="退单商品统计" :contentHeight="(homeData.refundList.length*40+10)+''">
                    <div v-for="item in homeData.refundList" class="goodsBox clearfix">
                        <div class="goodName left" v-text="item.productName" :title="item.productName"></div>
                        <div class="goodPrice right" v-text="'￥'+item.amount.toFixed(2)"></div>
                        <div class="number right" v-text="'×'+item.quantity"></div>
                    </div>
                    <!-- <div class="totalBox">
                        <span class="totalName">总金额</span>
                        <span class="totalNumber" v-text="'￥'+homeData.refundSummary.amount"></span>
                    </div> -->
                </accordion-item>
            </accordion>
        </scroll>
    </div>
</template>

<script type="text/javascript">
import echarts from "echarts";
export default {
  props: ["storeId"],
  data() {
    return {
      nowItem:{},//当前所选的分类
      showNowChild:false,
      nowDateParam:'',
      nowChild:[],//当前选择的分类下面的商品信息
      startDate: new Date().Format("yyyy-MM-dd"), //
      endDate: new Date().Format("yyyy-MM-dd"), //
      homeData: {
        amount: 0,
        alipayCash: 0,
        wechatCash: 0,
        cash: 0,
        alipay: 0,
        wechat: 0,
        profit: 0,
        hourly: [],
        salesSummary: {
          quantity: 0,
          amount: 0
        },
        stockSummary: {
          quantity: 0,
          amount: 0
        },
        refundSummary: {
          quantity: 0,
          amount: 0
        },
        salesList: [],
        refundList: [],
        salesItems:[]
      },
      getDataBtn: true,
      dataForIncome: [],//收入的相关数据
      dataForExpend: [],//支出的相关数据
      pie: null, // 收入饼状图
      pieForExpend: null, //支出饼状图
      nowDate: "",//当前日期
      timestamp: 0, //当前时间戳
      newTimestamp: 0, //变化后的时间戳
      totalAmount:0,
      wechat:0,
      ali:0,
      cash:0,
      amountInfo:[],//支付方式信息数组
      showPie:false//是否显示收入饼状图，如果当日没有收入数据则不显示
    };
  },
  watch:{
    newTimestamp(val){
      let date = new Date(val);
      let month = date.getMonth() + 1;
      let year = date.getFullYear();
      let day = date.getDate();
      let dateParam = `${year}-${month>9?month:'0'+month}-${day>9?day:'0'+day}`;
      this.nowDateParam = dateParam;
      $loading.show("加载中...");
      this.getData(dateParam);
      this.getGrade(dateParam);
    }
  },
  methods: {

    //获取分类下的商品信息
    
    getChild(item){
      if(this.nowItem.typeName != item.typeName){
        this.nowItem = item;
        this.$http({
          url:"boss-itemDetails",
          method:"GET",
          params:{
              from:this.nowDateParam,
              storeId:this.storeId,
              typeName:item.typeName
          }
        }).then(res=>{
            this.nowChild = res.data;
            this.showNowChild = true;
            console.log(res);
        });
      }else{
          this.nowItem = {};
          this.nowChild = [];
          this.showNowChild = false;
      }
    },
      //收入饼图
    drawPieForIncome(data) {
      let seriesData = data;
      let legendData = [];
      for(let i=0;i<seriesData.length;i++){
        legendData.push(seriesData[i].name);
      }
      if (this.pie) {
        this.pie.dispose();
      }
      this.pie = echarts.init(document.getElementById("pie"));
      setTimeout(() => {
        this.pie.setOption({
          tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b}: {c} ({d}%)"
          },
          // color: ["#55a8dc", "#6fcd58", "#e78d61"],
          legend: {
              orient: 'vertical',
              x: 'right',
              data:legendData,
              top:"middle",
              type:"scroll"
          },
          series: [
            {
              name: sessionStorage.getItem("storeName"),
              type: "pie",
              radius: ["40%", "70%"],
              center: ['25.9%', '50%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: "center"
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: "19",
                    fontWeight: "bold"
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: seriesData
            }
          ]
        });
      }, 200);
    },
    //支出饼图
    drawPieForExpend(datas) {
      let seriesData = [{ value: datas.active_count, name: "活跃" }];
      if (this.pieForExpend) {
        this.pieForExpend.dispose();
      }
      this.pieForExpend = echarts.init(
        document.getElementById("pie-for-expend")
      );
      setTimeout(() => {
        this.pieForExpend.setOption({
          tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b}: {c} ({d}%)"
          },
          color: ["#ccc", "#fb6e52", "#ffc655"],
          // legend: {
          //     orient: 'vertical',
          //     x: 'right',
          //     bottom:0,
          //     data:['流失','新增','活跃']
          // },
          series: [
            {
              name: sessionStorage.getItem("storeName"),
              type: "pie",
              radius: ["40%", "70%"],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: "center"
                },
                emphasis: {
                  show: true,
                  textStyle: {
                    fontSize: "19",
                    fontWeight: "bold"
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data: seriesData
            }
          ]
        });
      }, 200);
    },
    changeDate(type) {
      if (type === "add") {
        let date = new Date();
        let year = date.getFullYear();
        //往后一天
        this.newTimestamp += 24 * 60 * 60 * 1000;
        if (this.newTimestamp > this.timestamp) {
          this.newTimestamp = this.timestamp;
          return;
        } else {
          let newDate = new Date(this.newTimestamp);
          this.nowDate = newDate.getMonth() + 1 + "月" + newDate.getDate() + "日";
        }
      } else {
        let date = new Date();
        let year = date.getFullYear();
        //往前一天
        this.newTimestamp -= 24 * 60 * 60 * 1000;
        if (this.newTimestamp < this.timestamp) {
          let newDate = new Date(this.newTimestamp);
          this.nowDate = newDate.getMonth() + 1 + "月" + newDate.getDate() + "日";
        } else {
          this.newTimestamp = this.timestamp;
          return;
        }
      }
    },
    //获取收入支出数据
    getData(date) {
      //获取数据
      this.$http({
        url:"get-storeBill",
        method:"GET",
        params:{
          storeId:this.storeId,
          time:date,
          source:"boss",
          type:"DAY"
        }
      }).then(res=>{
          this.showPie = true;
          let data = res.data;
          let billInfo = JSON.parse(data.adminPayBill);
          this.amountInfo = billInfo.amount;
          let incomeData = [];
          if(billInfo.adminPayBill.length){
            if (this.pie) {
              this.pie.dispose();
            }
            // 提取信息
            for(let i = 0;i<billInfo.adminPayBill.length;i++){
              let amountObj = {};
              amountObj.value = Number(billInfo.adminPayBill[i].amount).toFixed(2);
              amountObj.count = billInfo.adminPayBill[i].count;
              switch (billInfo.adminPayBill[i].channel) {
                // case "pay.weixin.micropay":
                //   amountObj.name = "微信刷卡";
                //   amountObj.itemStyle = { normal: { color: "#e29fbf" } };
                //   break;
                // case "pay.alipay.micropay":
                //   amountObj.name = "支付宝刷卡";
                //   amountObj.itemStyle = { normal: { color: "#d69947" } };
                //   break;
                // case "pay.jdpay.micropay":
                //   amountObj.name = "京东刷卡";
                //   amountObj.itemStyle = { normal: { color: "#d17c42" } };
                //   break;
                case "jdMicroPay":
                  amountObj.name = "京东刷卡";
                  amountObj.itemStyle = { normal: { color: "#d17c42" } };
                  break;
                // case "pay.qq.micropay":
                //   amountObj.name = "QQ钱包刷卡";
                //   amountObj.itemStyle = { normal: { color: "#b3c125" } };
                //   break;
                case "qqMicroPay":
                  amountObj.name = "QQ钱包刷卡";
                  amountObj.itemStyle = { normal: { color: "#b3c125" } };
                  break;
                // case "pay.shiming.micropay":
                //   amountObj.name = "会员卡";
                //   amountObj.itemStyle = { normal: { color: "#1c9cba" } };
                //   break;
                case "smMicroPay":
                  amountObj.name = "会员卡";
                  amountObj.itemStyle = { normal: { color: "#1c9cba" } };
                  break;
                // case "pay.unionpay.micropay":
                //   amountObj.name = "银联支付";
                //   amountObj.itemStyle = { normal: { color: "#ff9e9c" } };
                //   break;
                case "unionPay":
                  amountObj.name = "银联支付";
                  amountObj.itemStyle = { normal: { color: "#ff9e9c" } };
                  break;
                // case "pay.bestpay.micropay":
                //   amountObj.name = "翼支付";
                //   amountObj.itemStyle = { normal: { color: "#ea7f5e" } };
                //   break;
                case "wingPayAmount":
                  amountObj.name = "翼支付";
                  amountObj.itemStyle = { normal: { color: "#ea7f5e" } };
                  break;
                // case "pay.weixin.native":
                //   amountObj.name = "微信扫码";
                //   amountObj.itemStyle = { normal: { color: "#8ecc52" } };
                //   break;
                // case "pay.alipay.native":
                //   amountObj.name = "支付宝扫码";
                //   amountObj.itemStyle = { normal: { color: "#41bbd8" } };
                //   break;
                case "CASH":
                  amountObj.name = "现金";
                  amountObj.itemStyle = { normal: { color: "#3bbddb" } };
                  break;
                case "cashAmount":
                  amountObj.name = "现金";
                  amountObj.itemStyle = { normal: { color: "#3bbddb" } };
                  break;
                case "WECHATPAY":
                  amountObj.name = "微信";
                  amountObj.itemStyle = { normal: { color: "#51c332" } };
                  break;
                case "wechatAmount":
                  amountObj.name = "微信";
                  amountObj.itemStyle = { normal: { color: "#51c332" } };
                  break;
                case "ALIPAY":
                  amountObj.name = "支付宝";
                  amountObj.itemStyle = { normal: { color: "#56abe4" } };
                  break;
                case "alipayAmount":
                  amountObj.name = "支付宝";
                  amountObj.itemStyle = { normal: { color: "#d69947" } };
                  break;
                case "UNIONPAY":
                  amountObj.name = "银联";
                  amountObj.itemStyle = { normal: { color: "#ff9e9c" } };
                  break;
                case "ALIPAY_CASH":
                  amountObj.name = "支付宝线下";
                  amountObj.itemStyle = { normal: { color: "#d69947" } };
                  break;
                case "WECHATPAY_CASH":
                  amountObj.name = "微信线下";
                  amountObj.itemStyle = { normal: { color: "#51c332" } };
                  break;
                case "COUPON":
                  amountObj.name = "优惠券";
                  amountObj.itemStyle = { normal: { color: "#619ce2" } };
                  break;
                case "couponAmount":
                  amountObj.name = "优惠券";
                  amountObj.itemStyle = { normal: { color: "#619ce2" } };
                  break;
                case "MEMBER":
                  amountObj.name = "会员";
                  amountObj.itemStyle = { normal: { color: "#1c9cba" } };
                  break;
                case "memberAmount":
                  amountObj.name = "会员";
                  amountObj.itemStyle = { normal: { color: "#1c9cba" } };
                  break;
                case "memberRechargeAmount":
                  amountObj.name = "会员充值";
                  amountObj.itemStyle = { normal: { color: "#1c9cba" } };
                  break;
                default:
                  break;
              }
              amountObj.name = `${amountObj.name}:${amountObj.value}元`
              // amountObj[billInfo.amount[i][0]] =  billInfo.amount[i][1];
              incomeData.push(amountObj);
            }
            console.log(incomeData);
            setTimeout(()=>{
              this.drawPieForIncome(incomeData);
            },300);
          }else{
            this.showPie = false;
            if (this.pie) {
              this.pie.dispose();
            }
          }

          // this.wechat = data.wx;
          // this.ali = data.ali;
          // this.cash = data.cash;
          this.totalAmount = data.allAmount;
      });
      // this.$http.get("/get-bill?storeId="+this.storeId).then(res => {
      //   this.dataForIncome = res.data;
      //   for (var i = 0, len = 7 - res.data.length; i < len; i++) {
      //     let obj = {
      //       active_count: 0,
      //       biz_date: new Date().getTime() - 24 * 3600 * 1000 * (7 - i),
      //       lost_count: 0,
      //       new_count: 0,
      //       sleep_count: 0,
      //       total: 0
      //     };
      //     this.dataForIncome.splice(i, 0, obj);
      //   }
      //   this.drawPieForIncome(
      //     this.dataForIncome[this.dataForIncome.length - 1]
      //   );
      //   this.drawPieForExpend(
      //     this.dataForIncome[this.dataForIncome.length - 1]
      //   );
      // });
    },
    // 折线图
    drawLineChart(data) {
      let timeArr = []; // 时间数组

      let numArr1 = []; // 销售数量
      let numArr2 = []; // 销售额

      if (data[0].date) {
        for (let i = 0, len = data.length; i < len; i++) {
          timeArr.push(data[i].date + "日");
          numArr1.push(data[i].quantity);
          numArr2.push(data[i].amount);
        }
      } else {
        for (let i = 0, len = data.length; i < len; i++) {
          timeArr.push(data[i].hour + ":00");
          numArr1.push(data[i].quantity);
          numArr2.push(data[i].amount);
        }
      }
      echarts.init(document.getElementById("chartLine")).setOption({
        tooltip: {
          trigger: "axis"
        },
        color: ["#f48080"],
        legend: {
          data: [
            { name: "销售额", textStyle: { color: "#666", fontSize: 12 } }
          ],
          bottom: 0,
          itemHeight: 8
        },
        grid: {
          left: "3%",
          right: "5%",
          bottom: "17%",
          top: "10%",
          containLabel: true
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: timeArr,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#ddd"
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: "#444"
            }
          }
        },
        yAxis: [
          {
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "#ddd"
              }
            },
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              textStyle: {
                color: "#444",
                fontSize: 12
              }
            }
          }
        ],
        series: [
          {
            name: "销售额",
            type: "line",
            smooth: true,
            data: numArr2,
            itemStyle: { normal: { label: { show: true } } }
          }
        ]
      });
    },
    // 选择日期
    selDate() {
      if (new Date(this.startDate).getTime() > new Date(this.endDate).getTime()) {
        $toast.show("开始时间不能大于结束时间", 2000).then(() => {});
        return;
      }

      if (!this.getDataBtn) {
        return;
      }
      this.getDataBtn = false;

      this.$http.get(
          "index?storeId=" +
            this.storeId +
            "&from=" +
            this.startDate +
            "&to=" +
            this.endDate
        )
        .then(res => {
          this.homeData = res.data;
          if (res.data.datelyList[0]) {
            this.drawLineChart(res.data.datelyList);
          } else {
            this.drawLineChart(res.data.hourlyList);
          }
          this.getDataBtn = true;
        })
        .catch(() => {
          this.getDataBtn = true;
        });
    },
    //获取销售业绩
    getGrade(date){
        this.$http.get(
          "index?storeId=" +
            this.storeId +
            "&from=" +
            date +
            "&to=" +
            date
        )
        .then(res => {
          if(res.status === 200){
            $loading.hide();
            this.homeData = res.data;
            if (res.data.datelyList[0]) {
              this.drawLineChart(res.data.datelyList);
            } else {
              this.drawLineChart(res.data.hourlyList);
            }
            this.getDataBtn = true;
          }
        })
        .catch(() => {
          this.getDataBtn = true;
        });
    },
    setStartDate(val) {
      this.startDate = val;
    },
    setEndDate(val) {
      this.endDate = val;
      this.selDate();
    }
  },
  created() {},
  mounted() {
    document.title = "销售统计";
    setTimeout(() => {
      this.selDate();
    }, 500);
    //初始化时间
    let date = new Date();
    //获取当前时间（不包含时分秒）的时间戳
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let day = date.getDate();
    let nowTimestamp = new Date(`${year}/${month}/${day}`).getTime();
    //计算出昨天的时间戳,之前只能查询前一天的数据，所以这里计算了一下时间，现在可以查当日的数据
    let prevDateTimestamp = nowTimestamp- 24 * 60 * 60 * 1000;
    //初始时间两个时间戳一致
    // this.timestamp = prevDateTimestamp;
    // this.newTimestamp = prevDateTimestamp;
    this.timestamp = nowTimestamp;
    this.newTimestamp = nowTimestamp;
    //根据昨天的时间戳，获取昨天的日期
    let prevDate = new Date(prevDateTimestamp);
    let prevMonth = prevDate.getMonth() + 1;
    let prevYear = prevDate.getFullYear();
    let prevDay = prevDate.getDate();
    //昨天的日期
    // this.nowDate = prevMonth + "月" + prevDay + "日";
    //今天的日期
    this.nowDate = month + "月" + day + "日";
    // 获取数据
    let dateParam = `${year}-${month>9?month:'0'+month}-${day>9?day:'0'+day}`
    this.getData(dateParam);
  }
};
</script>
<style lang="scss" scoped>
@import "saleStatic";
</style>
